package com.briup.ch13;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ConcurrentModificationException;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/21
 * @Description:
 */
public class Test05 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获得字节码对象
        Class<?> c= Class.forName("com.briup.ch13.Student");
        //获取构造器数组
        //获得公开的构造器数组
        Constructor<?>[] cons1=c.getConstructors();
        for(Constructor<?> con:cons1){
            System.out.println(con.toString());
        }
        System.out.println("--------------------------");
        //获得所有构造器数组,包括私有构造器
        Constructor<?>[] cons2=c.getDeclaredConstructors();
        for(Constructor<?> con:cons2){
            System.out.println(con.toString());
        }
        //获得指定的构造器
        Constructor<?> con=c.getConstructor(String.class,int.class);
        System.out.println(con.toString());
        //获得私有构造器
        Constructor<?> con2=c.getDeclaredConstructor(String.class,int.class);
        System.out.println(con2.toString());

        //借助字节码实例化对象
        Student s=(Student)con.newInstance("Tom",18);
        System.out.println(s.getName()+","+s.getAge());
        Student s2=(Student)con2.newInstance("Jerry",19);
        s2.setAge(20);
        System.out.println(s2.getName()+","+s2.getAge());
        con2.setAccessible(true);//允许访问私有构造器
        s2.setName("Mary");
        System.out.println(s2.getName()+","+s2.getAge());

        Constructor<?> cons3=c.getConstructor(String.class,int.class,String.class);
        cons3.setAccessible(true);
        Student s3=(Student)cons3.newInstance("Lily",20,"Male");
        System.out.println(s3.getName()+","+s3.getAge()+","+s3.getMajor());


    }
}
